<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2020/8/5
 * Time: 17:05
 */

namespace app\admin\controller;


use think\Exception;

class Trade extends Common
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function cancelMatch()
    {
        $id = input('id');
        $order = db('trade_order')->where('id', $id)->whereIn('status', [2, 3])->find();
        if (empty($order)) {
            $this->ajaxError('订单不存在');
        }else{
            $res = db('trade_order')
                ->where('id', $id)
                ->update([
                    'sell_user_id'=>0,
                    'status'=>1,
                    'match_time'=>0,
                    'pay_time'=>0,
                    'sure_time'=>0,
                    'pay_type'=>0,
                    'pay_img'=>0,
                ]);
            if(!empty($res)){
                $this->ajaxSuccess('操作成功');
            }else{
                $this->ajaxError('操作失败');
            }
        }
    }

    public function delOrder()
    {
        $id = input('id');
        $order = db('trade_order')->where('id', $id)->find();
        if (empty($order)) {
            $this->ajaxError('订单不存在');
        }else{
            $res = db('trade_order')
                ->where('id', $id)
                ->delete();
            if(!empty($res)){
                $this->ajaxSuccess('操作成功');
            }else{
                $this->ajaxError('操作失败');
            }
        }
    }

    public function sureOrder()
    {
        $order_id = input('id');
        $order = \db('trade_order')->where('id', $order_id)->where('status', 3)->find();
        if(empty($order)){
            $this->ajaxError('订单状态异常');
        }

        try {
            \db()->startTrans();;
            $update_data = [
                'status'=>4,
                'sure_time'=>now_datetime()
            ];
            $res = \db('trade_order')->where('id', $order_id)->update($update_data);
            if(empty($res)){
                throw new Exception('操作失败，请刷新后重试');
            }else{
                $insert_data = [
                    "uid"=>$order['user_id'],
                    "isadd"=>1,
                    "nums"=>$order['num'],
                    'fromuid'=>0,
                    "ctime"=>now_datetime(),
                    "info"=>"求购SCB获得"
                ];
                \db('mybot')->insert($insert_data);
                \db('user')->where('id', $order['user_id'])->setInc('mybot', $order['num']);
                \db()->commit();
                $this->ajaxSuccess('操作成功');
            }
        }catch (\Exception $e){
            \db()->rollback();
            $this->ajaxError($e->getMessage());
        }

    }

    public function order()
    {
        $this->templateTitle("交易订单");
        $order = \db('trade_order')->alias("or")->join("user buy", "or.user_id=buy.id", "left")->join("user match", "match.id=or.sell_user_id", "left");
        $param = input("get.");
        if (isset($param["id"]) && $param["id"] != "") {
            $order->where("or.id", $param["id"]);
        }

        if (isset($param["userinfo"]) && $param["userinfo"] != "") {
            $order->where("buy.username|buy.selfphone", $param["userinfo"]);
        }

        if (isset($param["time_range"]) && $param["time_range"] != "") {
            list($start_time, $end_time) = explode("~", $param["time_range"]);
        } else {
            $start_time = date("Y-m-d", strtotime("-7 day"));
            $end_time = date("Y-m-d");
        }
        $order->where("or.create_time", ">", strtotime($start_time));
        $order->where("or.create_time", "<", strtotime($end_time) + 86400);
        $this->assign("range_start", ["time_range" => $start_time]);
        $this->assign("range_end", ["time_range" => $end_time]);

        if (isset($param["status"]) && $param["status"] != "") {
            $order->where("or.status", $param["status"]);
        }

        if (isset($param["sell_user_id"]) && $param["sell_user_id"] != "") {
            $order->where("match.username|match.selfphone", $param["sell_user_id"]);
        }
        //获取订单列表
        $list = $order->field("or.*, buy.username b_username, buy.selfphone b_selfphone, match.username m_username, match.selfphone m_selfphone")
            ->order("or.id DESC")
            ->paginate(10);
        $this->assign("list", $list);
        $this->assign("param", $param);

        $bar['buyall'] = \db('trade_order')->sum('price');
        $bar['buyok'] = \db('trade_order')->whereIn('status', [3, 4])->sum('price');
        $bar['buying'] = ($bar['buyall'] - $bar['buyok']);
        $status_arr = [
            '1' => [
                "text" => "待出售",
                "color" => "label-danger",
            ],
            '2' => [
                "text" => "已配对，待支付",
                "color" => "label-warning",
            ],
            '3' => [
                "text" => "已支付待，确认",
                "color" => "label-primary",
            ],
            '4' => [
                "text" => "已完成",
                "color" => "label-success",
            ],
        ];
        $this->assign('status', $status_arr);
        $this->assign("all_money", $bar);
        return $this->fetch();
    }

    /**
     * 交易行情
     */
    public function index()
    {
        $list = db('trade_timeline')->order('day_time desc')->paginate(15);
        $this->assign('list', $list);
        //判断是否需要开启添加价格按钮
        $today = db('trade_timeline')->where('day_time', date('Y-m-d', strtotime('+1 day')))->find();
        if (empty($today)) {
            $this->assign('can_add', 1);
        } else {
            $this->assign('can_add', 0);
        }
        return $this->fetch();
    }

    /**
     * 添加价格
     */
    public function add()
    {
        $id = input('id', 0);
        $info = db('trade_timeline')->where('id', $id)->find();
        if (request()->isAjax()) {
            $data = input('post.');
            $data['update_time'] = now_datetime();
            if (empty($id)) {
                //插入新纪录
                $data['day_time'] = date('Y-m-d', strtotime('+1 day'));
                $res = db('trade_timeline')->insert($data);
            } else {
                $res = db('trade_timeline')->where('id', $id)->update($data);
            }
            if ($res) {
                $this->ajaxSuccess('编辑成功');
            } else {
                $this->ajaxError('编辑失败');
            }

        } else {
            $this->layoutModal();
            $this->assign('info', $info);
            return $this->fetch('add');
        }

    }

}